//
//  APIConnection.m
//  Ezi2u
//
//  Created by mac on 16/9/26.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "APIConnection.h"
#import "CommonDefines.h"
static APIConnection * _instance;

@implementation APIConnection
+ (APIConnection *) shareInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[APIConnection alloc] init];
    });
    
    return _instance;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        // timeout set
        [AFHTTPRequestOperationManager manager].requestSerializer.timeoutInterval = API_TIMEOUT;
        [AFHTTPRequestOperationManager manager].requestSerializer.cachePolicy = NSURLRequestReturnCacheDataElseLoad;
    }
    return self;
}

+(id)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}

-(id)copyWithZone:(NSZone *)zone{
    return _instance;
}

-(void)get:(NSString *)url apiFinish:(APIFinish)apiFinish netError:(Error)netError{
    NSString *requestPath = [API_HOST stringByAppendingPathComponent:url];
    NSLog(@"GET_URL==%@",requestPath);
    AFHTTPRequestOperationManager *manager =[AFHTTPRequestOperationManager manager];
    [manager GET:requestPath parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"GET: %@\nresponse: %@", requestPath, responseObject);NSDictionary *accessDict = [NSDictionary dictionaryWithDictionary:responseObject];
        NSString *message = [accessDict objectForKey:@"re_message"];
        NSArray  *array = [accessDict objectForKey:@"re_result"];
        apiFinish(array?array:NULL,message);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        netError(@"网络请求失败");
        NSLog(@"NSError_Server==%@",[error description]);
    }];
}

-(void)post:(NSString *)url data:(NSDictionary *)data apiFinish:(APIFinish)apiFinish netError:(Error)netError{
    NSString *requestPath = [API_HOST stringByAppendingPathComponent:url];
    NSLog(@"POST_URL==%@",requestPath);
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:requestPath parameters:data success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"POST: %@\nresponse: %@", requestPath, responseObject);NSDictionary *accessDict = [NSDictionary dictionaryWithDictionary:responseObject];
        NSString *message = [accessDict objectForKey:@"re_message"];
        NSArray  *array = [accessDict objectForKey:@"re_result"];
        NSNumber *code = [accessDict objectForKey:@"re_code"];
        if ([code integerValue]==0) {
            apiFinish(array?array:NULL,message);
        }else{
            netError(message);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"NSError_Server==%@",[error description]);
        netError(@"网络请求失败");
    }];
}
@end
